package com.hcinfos.gsoo.ui;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.hcinfos.gsoo.GsooApplication;
import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.adapter.UploadImgAdapter;
import com.hcinfos.gsoo.config.Common;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.enity.ImageInfo;
import com.hcinfos.gsoo.enity.ViewSuppDetail;
import com.hcinfos.gsoo.enity.ViewSuppSearchExt;
import com.hcinfos.gsoo.https.HttpClientUtil;
import com.hcinfos.gsoo.util.CommonUtil;
import com.hcinfos.gsoo.util.DialogUtil;
import com.hcinfos.gsoo.util.ImageUtil;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.SharePreferenceUtil;

/**
 * 上传图片
 * 
 * @author xi
 * 
 */
public class UploadImgActivity extends Activity implements OnClickListener {
	private TextView reg_tv;
	private ImageButton left_ib;
	private TextView center_tv;

	private Gallery gallery;
	private View addMenuView;
	private Button pai;
	private Button album;
	private Button cancel;

	private UploadImgAdapter galleryAdapter;
	private List<ImageInfo> galleryList;
	private PopupWindow menuWindow;

	private final int GET_IMG_RESULT_CODE = 0x1120;
	private final int CAMERA_IMG_RESULT_CODE = GET_IMG_RESULT_CODE + 1;
	private final int LOOK_IMG_RESULT_CODE = GET_IMG_RESULT_CODE + 2;
	private final int UPLOAD_SUCCESS = GET_IMG_RESULT_CODE + 3;
	private final int UPLOAD_FAIL = GET_IMG_RESULT_CODE + 4;

	private Dialog dialog;
	private SharePreferenceUtil util;
	private Button submit_button;
	private Context context;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;
		context = this;
		setContentView(R.layout.activity_upload);
		util = new SharePreferenceUtil(this, "setting");
		dialog = DialogUtil.createProgressDialog(this, "图片添加", "图片信息添加中");
		initRes();
	}

	private void initRes() {
		center_tv = (TextView) findViewById(R.id.center_tv);
		center_tv.setText("上传图片");
		left_ib = (ImageButton) findViewById(R.id.left_ib);
		left_ib.setOnClickListener(this);
		reg_tv = (TextView) findViewById(R.id.reg_tv);
		reg_tv.setVisibility(View.GONE);

		gallery = (Gallery) findViewById(R.id.gallery);

		LayoutInflater inflater = getLayoutInflater();
		addMenuView = inflater.inflate(R.layout.addpic, null);
		pai = (Button) addMenuView.findViewById(R.id.pai);
		pai.setOnClickListener(this);
		album = (Button) addMenuView.findViewById(R.id.album);
		album.setOnClickListener(this);
		cancel = (Button) addMenuView.findViewById(R.id.cancel);
		cancel.setOnClickListener(this);

		galleryList = new ArrayList<ImageInfo>();
		ImageInfo info = new ImageInfo();
		info.setBitmap(BitmapFactory.decodeResource(getResources(),
				R.drawable.upload_img_icon));
		galleryList.add(info);
		galleryAdapter = new UploadImgAdapter(this, galleryList);
		gallery.setAdapter(galleryAdapter);
		gallery.setOnItemClickListener(galleryItemClickListener);
		submit_button = (Button) findViewById(R.id.submit_button);
		submit_button.setOnClickListener(this);
	}

	private OnItemClickListener galleryItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {

			if (position == 0) {
				if (menuWindow == null) {
					menuWindow = getResultWindow();
				}
				menuWindow.showAtLocation(
						UploadImgActivity.this.findViewById(R.id.main),
						Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
			} else {
				galleryAdapter.setPosition(position);
				galleryAdapter.notifyDataSetChanged();
			}
		}
	};

	public PopupWindow getResultWindow() {
		final PopupWindow resultWindow = new PopupWindow();
		// 设置按钮监听
		// 设置SelectPicPopupWindow的View
		resultWindow.setContentView(addMenuView);
		// 设置SelectPicPopupWindow弹出窗体的宽
		resultWindow.setWidth(LayoutParams.FILL_PARENT);
		// 设置SelectPicPopupWindow弹出窗体的高
		resultWindow.setHeight(LayoutParams.WRAP_CONTENT);
		// 设置SelectPicPopupWindow弹出窗体可点击
		resultWindow.setFocusable(true);
		// 设置SelectPicPopupWindow弹出窗体动画效果
		resultWindow.setAnimationStyle(R.style.AnimBottom);
		// 实例化一个ColorDrawable颜色为半透明
		ColorDrawable dw = new ColorDrawable(Color.argb(125, 0, 0, 0));
		// 设置SelectPicPopupWindow弹出窗体的背景
		resultWindow.setBackgroundDrawable(dw);
		// mMenuView添加OnTouchListener监听判断获取触屏位置如果在选择框外面则销毁弹出框
		addMenuView.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent event) {
				int height = addMenuView.findViewById(R.id.pop_rl).getTop();
				int y = (int) event.getY();
				if (event.getAction() == MotionEvent.ACTION_UP) {
					if (y < height) {
						resultWindow.dismiss();
					}
				}
				return true;
			}
		});
		return resultWindow;
	}

	private ViewSuppSearchExt detail;

	@Override
	protected void onResume() {
		super.onResume();
		detail = (ViewSuppSearchExt) getIntent().getSerializableExtra(
				"shopDetail");
		if (detail == null)
			return;
	}

	private Intent intent;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.left_ib:
			finish();
			break;
		case R.id.pai:
			menuWindow.dismiss();
			intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			startActivityForResult(intent, CAMERA_IMG_RESULT_CODE);
			break;
		case R.id.cancel:
			menuWindow.dismiss();
			break;
		case R.id.album:
			menuWindow.dismiss();
			if (galleryList.size() > 5) {
				Toast.makeText(this, "一次最多可上传5张图片", 500).show();
				return;
			}
			intent = new Intent(Intent.ACTION_GET_CONTENT);
			intent.addCategory(Intent.CATEGORY_OPENABLE);
			intent.setType("image/*");
			startActivityForResult(intent, GET_IMG_RESULT_CODE);
			break;
		case R.id.submit_button:
			if (galleryList.size() <= 1) {
				Toast.makeText(context, "上传图片不能为空", 500).show();
			} else {
				if (dialog != null)
					dialog.show();
				uploadImg();
			}
			break;
		}
	}

	private void uploadImg() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				InputStream[] files = null;
				String[] fileNames = null;
				if (galleryList.size() <= 1)
					return;
				files = new InputStream[galleryList.size() - 1];
				fileNames = new String[galleryList.size() - 1];
				for (int i = 1; i < galleryList.size(); i++) {
					ImageInfo info = galleryList.get(i);
					Bitmap bitmap = BitmapFactory.decodeFile(info.getPath());
					files[i - 1] = new ByteArrayInputStream(CommonUtil
							.bitmap2Bytes(bitmap));
					fileNames[i - 1] = info.getName();

				}
				if (files.length == 0) {
					LogUtil.d("wxf", "null....");
					return;
				}
				String result = HttpClientUtil.uploadImg(context, null, files,
						fileNames, Urls.UPLOAD_IMG + "suppId=" + detail.getId());
				Log.e("wxf", "uploadResult=" + result);
				try {
					if (result != null) {
						JSONObject obj = new JSONObject(result);
						String message = obj.getString("message");
						int state = obj.getInt("state");
						JSONArray array = obj.getJSONArray("rows");
						if (state == 200) {
							if (array.length() > 0) {
								JSONObject arrayObj = array.getJSONObject(0);
								String id = arrayObj.getString("id");
								String imgAddress = arrayObj
										.getString("imgAddr");
								detail.setImgId(id);
								detail.setImgAddr(imgAddress);
							}

							Message msg = handler.obtainMessage();
							msg.what = UPLOAD_SUCCESS;
							handler.sendMessage(msg);
						} else {
							Message msg = handler.obtainMessage();
							msg.what = UPLOAD_FAIL;
							msg.obj = message;
							handler.sendMessage(msg);
						}
					} else {
						Message msg = handler.obtainMessage();
						msg.what = UPLOAD_FAIL;
						handler.sendMessage(msg);
					}
				} catch (Exception e) {
					Message msg = handler.obtainMessage();
					msg.what = UPLOAD_FAIL;
					handler.sendMessage(msg);
				}
			}
		}).start();
	}

	Handler handler = new Handler() {

		public void handleMessage(Message msg) {
			if (dialog != null)
				dialog.dismiss();
			switch (msg.what) {
			case UPLOAD_FAIL:
				Toast.makeText(context, "抱歉上传失败!", 500).show();
				break;
			case UPLOAD_SUCCESS:
				Toast.makeText(context, "上传成功!", 500).show();
				Intent intent = new Intent(UploadImgActivity.this,
						ShopDetailActivity.class);
				GsooApplication.tempSuppExt = detail;
				startActivity(intent);
				finish();
				break;
			}
		};
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case GET_IMG_RESULT_CODE:
			if (resultCode == RESULT_OK) {
				gallery.setVisibility(View.VISIBLE);
				String[] filePathColumn = { MediaStore.Images.Media.DATA };
				Cursor cursor = getContentResolver().query(data.getData(),
						filePathColumn, null, null, null);
				cursor.moveToFirst();

				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				String picturePath = cursor.getString(columnIndex);
				String newPath = CommonUtil.pngToJpgFromPath(picturePath);
				if (newPath == null) {
					Toast.makeText(this, "图片添加失败", 500).show();
					return;
				}
				File f = new File(newPath);
				LogUtil.e("wxf", "fileSize:" + f.length() + "//" + f.length()
						/ 1024);
				ImageInfo info = new ImageInfo();
				info.setPath(newPath);
				info.setName(System.currentTimeMillis() + ".jpg");
				LogUtil.d("wxf", "picturePath" + picturePath);
				galleryList.add(info);
				galleryAdapter.setDataChange(galleryList);

			}
			break;
		case CAMERA_IMG_RESULT_CODE:
			if (resultCode == RESULT_OK) {
				gallery.setVisibility(View.VISIBLE);
				Uri uri = data.getData();
				Bitmap newbitmap = null;
				Bitmap bitmap = null;
				String imgPath = null;
				if (uri != null) {
					Cursor cursor = getContentResolver().query(uri, null, null,
							null, null);
					cursor.moveToFirst();
					imgPath = cursor.getString(1); // 图片文件路径
					cursor.close();
					if (imgPath != null) {
						bitmap = (Bitmap) data.getExtras().get("data");
						newbitmap = ImageUtil.rotaingImageView(90, bitmap);
					}
				} else {
					Bundle extras = data.getExtras();
					bitmap = (Bitmap) extras.get("data");
					newbitmap = bitmap;
					imgPath = CommonUtil.getSDPath() + "/"
							+ System.currentTimeMillis() + ".jpg";
				}
				if (imgPath == null) {
					Toast.makeText(context, "获取图片失败", 500).show();
					return;
				}
				File file = new File(imgPath);
				FileOutputStream fos = null;
				try {
					fos = new FileOutputStream(file);
					newbitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
					fos.flush();
					fos.close();
					if (newbitmap != null && !newbitmap.isRecycled()) {
						newbitmap.recycle();
					}
					if (bitmap != null && !bitmap.isRecycled()) {
						bitmap.recycle();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
				ImageInfo info = new ImageInfo();
				info.setPath(imgPath);
				info.setName(System.currentTimeMillis() + ".jpg");
				LogUtil.d("wxf", "info:" + info);
				galleryList.add(info);
				galleryAdapter.setDataChange(galleryList);
			}
			break;
		}
	}
}
